<template>
  <div class="page-container">
    <h1 class="metro-title"><i class="metro-icon"></i>客流量分析</h1>

    <el-row :gutter="20">
      <el-col :span="6" v-for="card in statCards" :key="card.title">
        <el-card class="stat-card" :body-style="{ padding: '0px' }">
          <div class="stat-card-content">
            <div class="stat-card-icon" :style="{ backgroundColor: card.color }">
              <el-icon><component :is="card.icon" /></el-icon>
            </div>
            <div class="stat-card-info">
              <div class="stat-card-title">{{ card.title }}</div>
              <div class="stat-card-value">{{ card.value }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>每日客流量趋势</span>
              <el-select v-model="timeRange" placeholder="选择时间范围" @change="updateDailyFlowChart">
                <el-option label="最近7天" value="7" />
                <el-option label="最近14天" value="14" />
                <el-option label="最近30天" value="30" />
              </el-select>
            </div>
          </template>
          <div ref="dailyFlowChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>热门站点排行</span>
            </div>
          </template>
          <div ref="popularStationsChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>时段客流量分布</span>
            </div>
          </template>
          <div ref="hourlyDistributionChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>客流量分析报告</span>
            </div>
          </template>
          <div class="analysis-report">
            <h3>客流量总体情况</h3>
            <p>{{ overallAnalysis }}</p>
            
            <h3>热门站点分析</h3>
            <p>{{ stationAnalysis }}</p>
            
            <h3>时段分布分析</h3>
            <p>{{ timeAnalysis }}</p>
            
            <h3>发展建议</h3>
            <ul class="suggestions-list">
              <li v-for="(suggestion, index) in suggestions" :key="index">
                <el-icon><InfoFilled /></el-icon>
                <span>{{ suggestion }}</span>
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { usePassengerFlowStore } from '../../stores/passengerFlow'
import { Location, DataLine, DataAnalysis, Histogram, InfoFilled } from '@element-plus/icons-vue'

// 初始化客流量存储
const passengerFlowStore = usePassengerFlowStore()

// 图表DOM引用
const dailyFlowChartRef = ref<HTMLElement | null>(null)
const popularStationsChartRef = ref<HTMLElement | null>(null)
const hourlyDistributionChartRef = ref<HTMLElement | null>(null)

// 图表实例
let dailyFlowChart: echarts.ECharts | null = null
let popularStationsChart: echarts.ECharts | null = null
let hourlyDistributionChart: echarts.ECharts | null = null

// 时间范围选择
const timeRange = ref('7')

// 统计卡片数据
const statCards = reactive([
  {
    title: '总客流量',
    value: '0',
    icon: Histogram,
    color: '#1976d2',
  },
  {
    title: '今日客流量',
    value: '0',
    icon: DataLine,
    color: '#ff9800',
  },
  {
    title: '热门站点',
    value: '无数据',
    icon: Location,
    color: '#4caf50',
  },
  {
    title: '高峰时段',
    value: '无数据',
    icon: DataAnalysis,
    color: '#e91e63',
  },
])

// 分析报告文本
const overallAnalysis = computed(() => {
  const totalPassengers = passengerFlowStore.totalPassengers
  const dailyData = passengerFlowStore.dailyFlowData
  
  if (dailyData.length === 0) {
    return '暂无客流量数据，请先在基本查询功能中查看站点信息，系统将自动记录客流量数据。'
  }
  
  const avgDailyFlow = Math.round(totalPassengers / dailyData.length)
  
  return `系统累计记录客流量${totalPassengers}人次，覆盖${dailyData.length}天数据，日均客流量约${avgDailyFlow}人次。
  客流量数据反映了地铁站点的使用频率和受欢迎程度，可为地铁运营和城市规划提供重要参考。`
})

const stationAnalysis = computed(() => {
  const popularStations = passengerFlowStore.popularStations
  
  if (popularStations.length === 0) {
    return '暂无站点访问数据。'
  }
  
  const top3 = popularStations.slice(0, Math.min(3, popularStations.length))
  const stationNames = top3.map(s => s.name).join('、')
  
  return `根据客流量统计，${stationNames}等站点是最受欢迎的站点，客流量较大。
  这些站点通常位于商业中心、交通枢纽或人口密集区域，具有较高的商业价值和发展潜力。
  建议加强这些站点的客流管理和商业开发。`
})

const timeAnalysis = computed(() => {
  const hourlyData = passengerFlowStore.hourlyDistribution
  
  if (hourlyData.every(h => h === 0)) {
    return '暂无时段分布数据。'
  }
  
  // 找出高峰时段
  const peakHours: number[] = []
  const maxFlow = Math.max(...hourlyData)
  
  hourlyData.forEach((flow, hour) => {
    if (flow > maxFlow * 0.7) { // 流量超过最大值的70%视为高峰
      peakHours.push(hour)
    }
  })
  
  const peakHoursText = peakHours.map(h => `${h}:00-${h+1}:00`).join('、')
  
  return `客流量时段分布显示，${peakHoursText}是客流高峰时段。
  这些时段通常对应上下班高峰期或商业活动高峰期。
  建议在高峰时段增加列车运行频次，优化站内客流疏导，提高运营效率。`
})

const suggestions = computed(() => {
  return [
    '建议对热门站点进行商业空间优化，增加便民服务设施，提升乘客体验',
    '可考虑在客流高峰时段增加工作人员，优化客流疏导，减少拥堵情况',
    '对于客流量较低的站点，可以通过周边商业开发和交通接驳优化提升其使用率',
    '建议利用客流量数据指导广告投放和商业布局，提高商业价值',
    '可以考虑开发移动应用，提供实时客流量信息，帮助乘客避开高峰时段'
  ]
})

// 初始化图表
function initCharts() {
  // 每日客流量趋势图
  if (dailyFlowChartRef.value) {
    dailyFlowChart = echarts.init(dailyFlowChartRef.value)
    dailyFlowChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: [],
        axisLabel: {
          interval: 0,
          rotate: 30
        }
      },
      yAxis: {
        type: 'value',
        name: '客流量'
      },
      series: [
        {
          name: '客流量',
          type: 'line',
          data: [],
          smooth: true,
          lineStyle: {
            width: 3,
            color: '#1976d2'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: 'rgba(25, 118, 210, 0.5)'
                },
                {
                  offset: 1,
                  color: 'rgba(25, 118, 210, 0.1)'
                }
              ]
            }
          },
          markPoint: {
            data: [
              { type: 'max', name: '最大值' },
              { type: 'min', name: '最小值' }
            ]
          }
        }
      ]
    })
  }

  // 热门站点排行图
  if (popularStationsChartRef.value) {
    popularStationsChart = echarts.init(popularStationsChartRef.value)
    popularStationsChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        name: '客流量'
      },
      yAxis: {
        type: 'category',
        data: [],
        axisLabel: {
          interval: 0
        }
      },
      series: [
        {
          name: '客流量',
          type: 'bar',
          data: [],
          itemStyle: {
            color: function(params: any) {
              const colorList = [
                '#ff9800',
                '#4caf50',
                '#e91e63',
                '#9c27b0',
                '#673ab7',
                '#3f51b5',
                '#2196f3',
                '#03a9f4',
                '#00bcd4',
                '#009688'
              ]
              return colorList[params.dataIndex % colorList.length]
            }
          }
        }
      ]
    })
  }

  // 时段客流量分布图
  if (hourlyDistributionChartRef.value) {
    hourlyDistributionChart = echarts.init(hourlyDistributionChartRef.value)
    hourlyDistributionChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: '{b}:00-{b}:59<br/>{a}: {c}'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: Array.from({ length: 24 }, (_, i) => i),
        name: '小时',
        axisLabel: {
          formatter: '{value}:00'
        }
      },
      yAxis: {
        type: 'value',
        name: '客流量'
      },
      series: [
        {
          name: '客流量',
          type: 'bar',
          data: [],
          itemStyle: {
            color: function(params: any) {
              // 根据时段设置不同颜色
              if (params.dataIndex >= 7 && params.dataIndex <= 9) {
                return '#ff9800' // 早高峰
              } else if (params.dataIndex >= 17 && params.dataIndex <= 19) {
                return '#e91e63' // 晚高峰
              } else if (params.dataIndex >= 22 || params.dataIndex <= 5) {
                return '#9e9e9e' // 夜间
              } else {
                return '#4caf50' // 平峰
              }
            }
          },
          markArea: {
            itemStyle: {
              color: 'rgba(255, 152, 0, 0.2)'
            },
            data: [
              [{ xAxis: '7' }, { xAxis: '9' }],
              [{ xAxis: '17' }, { xAxis: '19' }]
            ]
          }
        }
      ]
    })
  }
}

// 更新每日客流量趋势图
function updateDailyFlowChart() {
  if (!dailyFlowChart) return

  const days = parseInt(timeRange.value)
  const flowData = passengerFlowStore.getRecentDaysFlow(days)
  
  // 按日期排序（从早到晚）
  const sortedData = [...flowData].sort((a, b) => 
    new Date(a.date).getTime() - new Date(b.date).getTime()
  )
  
  const dates = sortedData.map(item => formatDate(item.date))
  const values = sortedData.map(item => item.totalPassengers)
  
  dailyFlowChart.setOption({
    xAxis: {
      data: dates
    },
    series: [
      {
        data: values
      }
    ]
  })
}

// 更新热门站点排行图
function updatePopularStationsChart() {
  if (!popularStationsChart) return
  
  const popularStations = passengerFlowStore.popularStations
  
  // 只显示前10个站点
  const topStations = popularStations.slice(0, 10)
  
  const stationNames = topStations.map(station => station.name)
  const stationValues = topStations.map(station => station.count)
  
  popularStationsChart.setOption({
    yAxis: {
      data: stationNames
    },
    series: [
      {
        data: stationValues
      }
    ]
  })
  
  // 更新热门站点统计卡片
  if (topStations.length > 0) {
    statCards[2].value = topStations[0].name
  }
}

// 更新时段客流量分布图
function updateHourlyDistributionChart() {
  if (!hourlyDistributionChart) return
  
  const hourlyData = passengerFlowStore.hourlyDistribution
  
  hourlyDistributionChart.setOption({
    series: [
      {
        data: hourlyData
      }
    ]
  })
  
  // 更新高峰时段统计卡片
  if (hourlyData.some(h => h > 0)) {
    const maxHour = hourlyData.indexOf(Math.max(...hourlyData))
    statCards[3].value = `${maxHour}:00-${maxHour+1}:00`
  }
}

// 更新统计卡片数据
function updateStatCards() {
  // 总客流量
  statCards[0].value = passengerFlowStore.totalPassengers.toString()
  
  // 今日客流量
  const today = new Date().toISOString().split('T')[0]
  const todayData = passengerFlowStore.dailyFlowData.find(data => data.date === today)
  statCards[1].value = todayData ? todayData.totalPassengers.toString() : '0'
}

// 格式化日期
function formatDate(dateStr: string) {
  const date = new Date(dateStr)
  return `${date.getMonth() + 1}/${date.getDate()}`
}

// 加载统计数据
function loadStatisticsData() {
  // 更新统计卡片
  updateStatCards()
  
  // 更新图表
  updateDailyFlowChart()
  updatePopularStationsChart()
  updateHourlyDistributionChart()
}

// 窗口大小变化时重新调整图表大小
function handleResize() {
  dailyFlowChart?.resize()
  popularStationsChart?.resize()
  hourlyDistributionChart?.resize()
}

onMounted(() => {
  // 初始化图表
  initCharts()
  
  // 加载数据
  loadStatisticsData()
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  
  // 销毁图表实例
  dailyFlowChart?.dispose()
  popularStationsChart?.dispose()
  hourlyDistributionChart?.dispose()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.metro-title {
  margin-bottom: 20px;
  color: #1976d2;
  font-size: 24px;
  display: flex;
  align-items: center;
}

.metro-icon {
  display: inline-block;
  width: 24px;
  height: 24px;
  margin-right: 8px;
  background-color: #1976d2;
  border-radius: 50%;
}

.stat-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.stat-card-content {
  display: flex;
  padding: 20px;
}

.stat-card-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  border-radius: 8px;
  margin-right: 15px;
  color: white;
  font-size: 24px;
}

.stat-card-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.stat-card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.chart-row {
  margin-top: 20px;
}

.chart-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 350px;
  width: 100%;
}

.analysis-report {
  padding: 10px;
}

.analysis-report h3 {
  margin-top: 20px;
  margin-bottom: 10px;
  color: #1976d2;
  font-size: 18px;
}

.analysis-report p {
  line-height: 1.6;
  color: #606266;
  margin-bottom: 15px;
}

.suggestions-list {
  list-style: none;
  padding: 0;
}

.suggestions-list li {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
  color: #606266;
}

.suggestions-list li .el-icon {
  color: #1976d2;
  margin-right: 8px;
  margin-top: 3px;
}
</style>
